package com.rookie.mystock.common.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
@Data
@NoArgsConstructor
public class ResponseObject implements Serializable {
    private static final String SUCCESS_STATE = "0";    // 访问成功
    private static final String FAIL_STATE = "1";   // 访问失败
    private static final String ERROR_STATE = "2";  // 系统错误

    private static final String SUCCESS_MSG = "操作成功";
    private static final String FAIL_MSG = "操作失败";
    private static final String ERROR_MSG = "程序错误";

    private String state;   // 请求返回状态码
    private String msg; // 请求返回信息
    private Object data;    // 请求返回的数据

    // 访问成功
    public static ResponseObject success(){
        return success(SUCCESS_MSG);
    }

    public static ResponseObject success(String msg){
        return success(msg, null);
    }

    public static ResponseObject success(String msg, Object data){
        return Builder.create().state(SUCCESS_STATE).msg(msg).data(data).build();
    }

    // 访问失败
    public ResponseObject fail(){
        return fail(FAIL_MSG);
    }

    public static ResponseObject fail(String msg){
        return fail(msg, null);
    }

    public static ResponseObject fail(String msg, Object data){
        return Builder.create().state(FAIL_STATE).msg(msg).data(data).build();
    }

    // 系统错误
    public static ResponseObject error(){
        return error(ERROR_MSG);
    }

    public static ResponseObject error(String msg){
        return error(msg);
    }

    public static ResponseObject error(String msg, Object data){
        return Builder.create().state(ERROR_STATE).msg(msg).data(data).build();
    }

    public ResponseObject(Builder builder){
        this.state = builder.state;
        this.msg = builder.msg;
        this.data = builder.data;
    }

    public static class Builder{
        private String state;
        private String msg;
        private Object data;

        public Builder(){
            super();
        }

        public Builder state(String state){
            this.state = state;
            return this;
        }

        public Builder msg(String msg){
            this.msg = msg;
            return this;
        }

        public Builder data(Object data){
            this.data = data;
            return this;
        }

        public static Builder create(){
            return new Builder();
        }

        public ResponseObject build(){
            ResponseObject responseObject = new ResponseObject(this);
            return responseObject;
        }
    }
}
